package stack;

import java.util.Arrays;

class StackNullException extends Exception{

    public StackNullException(String message) {
        System.out.println(message);;
    }
}

public class MyStack {
     int DEFAULT_CAPACITY=10;
    int[] elem=new int[DEFAULT_CAPACITY];
    int useSize=0;
    public MyStack() {
    }
    public int push(int n){
        //判满
        if (isFull()){
            //满了先扩容
            elem= Arrays.copyOf(elem,elem.length*2);
        }
        //扩容完事之后再||没满--->入栈
        elem[useSize]=n;
        useSize++;
        return n;
    }
    private boolean isFull(){
        return useSize==elem.length;
    }

    public int peek() throws StackNullException{
        if (!isEmpty()){
            //通过usesize--覆盖删除的手段来删除
            int ret=elem[useSize-1];
            return ret;
        }else throw new StackNullException("栈为空异常，无法正常获取栈顶元素");

    }

    public int pop() throws StackNullException{
        //出栈前先判断栈是否为空
        if (!isEmpty()){
            //通过usesize--覆盖删除的手段来删除
            int ret=elem[useSize-1];
            useSize--;
            return ret;
        }else throw new StackNullException("栈为空异常，无法正常出栈");


    }
    public boolean isEmpty(){
        return useSize==0;
    }
    //获取有效元素个数
    public int size(){
        return  useSize;
    }

}
